package com.qf.bo;

import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @USER: Administrator
 * @DATE: 2025/9/4 下午6:38
 * @VERSION: 1.0.0
 */
@Data
public class UserDetailsBO implements UserDetails {
    /**
     * 用户信息
     */
    private final UserBO userBO;

    public UserDetailsBO(UserBO userBO) {
        this.userBO = userBO;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = Collections.emptyList();
        if (userBO.getRoles() != null) {
            authorities = userBO.getRoles().stream().map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRoleCode())).collect(Collectors.toList());
        }

        return authorities.stream().filter(Objects::nonNull).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return new BCryptPasswordEncoder().encode(userBO.getPassword());
    }

    @Override
    public String getUsername() {
        return userBO.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return Objects.isNull(userBO.getAccountExpireTime()) || userBO.getAccountExpireTime().isAfter(LocalDateTime.now());
    }

    @Override
    public boolean isAccountNonLocked() {
        return userBO.getIsLocked() == 0;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return Objects.isNull(userBO.getCredentialsExpireTime()) || userBO.getCredentialsExpireTime().isAfter(LocalDateTime.now());
    }

    @Override
    public boolean isEnabled() {
        return userBO.getIsEnabled() == 1;
    }
}
